import { useEffect, useState } from "react";
import { HOME_URL } from "@/config";
import { connect } from "react-redux";
import { setTabsList } from "@/redux/modules/tabs/action";
import { routerArray } from "@/routers";
import { searchRoute } from "@/utils";
import { useLocation, useNavigate } from "react-router-dom";
import { Tabs } from "tdesign-react";
import "./index.less";

const { TabPanel } = Tabs;
const LayoutTabs = (props: any) => {
	const { tabsList } = props.tabs;
	const { themeConfig } = props.global;
	const { setTabsList } = props;
	const { pathname } = useLocation();
	const [activeValue, setActiveValue] = useState<string>(pathname);
	const navigate = useNavigate();
	useEffect(() => {
		addTabs();
	}, [pathname]);
	// click tabs
	const clickTabs = (path: any) => {
		console.log(path, navigate, "path");
		navigate(path);
	};
	// delete tabs
	const delTabs = (tabPath?: any) => {
		console.log(pathname, tabPath.value);
		if (tabPath === HOME_URL) return;
		if (pathname === tabPath) {
			tabsList.forEach((item: Menu.MenuOptions, index: number) => {
				if (item.path !== pathname) return;
				const nextTab = tabsList[index + 1] || tabsList[index - 1];
				if (!nextTab) return;
				navigate(nextTab.path);
			});
		}
		setTabsList(tabsList.filter((item: Menu.MenuOptions) => item.path !== tabPath.value));
	};
	const addTabs = () => {
		const route = searchRoute(pathname, routerArray);
		let newTabsList = JSON.parse(JSON.stringify(tabsList));
		if (tabsList.every((item: any) => item.path !== route.path)) {
			newTabsList.push({ title: route.meta!.title, path: route.path });
		}
		setTabsList(newTabsList);
		setActiveValue(pathname);
	};
	return (
		<div className="tabs">
			{!themeConfig.tabs && (
				<Tabs disabled={false} onChange={clickTabs} defaultValue={HOME_URL} value={activeValue}>
					{tabsList.map((item: Menu.MenuOptions) => {
						return (
							<TabPanel
								key={item.path}
								removable={item.path !== HOME_URL}
								label={item.title}
								value={item.path}
								onRemove={delTabs}
							></TabPanel>
						);
					})}
				</Tabs>
			)}
		</div>
	);
};

const mapStateToProps = (state: any) => state;
const mapDispatchToProps = { setTabsList };
export default connect(mapStateToProps, mapDispatchToProps)(LayoutTabs);
